<?php

namespace Scau\Common;

/**
 * 工具类
 * @package Scau\Common
 */
class Utils
{
    /**
     * @param string $url
     * @param bool $isPost
     * @param array $postParam
     * @param array $headers
     * @return bool|string
     */
    public static function httpCurl(string $url, $isPost = false, $postParam = [], $headers = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        if ($isPost === true) {
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postParam);
        }

        if ($headers) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    /**
     * 对URL参数进行编码
     * @param string $baseUrl
     * @param array $params
     * @return string
     */
    public static function urlencodeParameters($baseUrl, $params)
    {
        if (empty($params)) {
            return $baseUrl;
        }

        $urlParams = [];
        foreach ($params as $name => $value) {
            $urlParams[] = $name . '=' . urlencode($value);
        }
        return $baseUrl . '?' . implode('&', $urlParams);
    }
}